<template>
  <!-- 首页/权限管理/角色列表 -->
  <div>
    <!--  面包屑导航区  -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item><span>角色列表</span></el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
    <!--   添加角色区   -->
      <el-row>
        <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
      </el-row>

    <!--  角色列表区域 -->
      <el-table
        :data="roleList" border stripe>
        <!-- 展开列  -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom', i1 === 0 ? 'bdTop' : '','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!--  渲染一级权限  -->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 通过 for 循环嵌套渲染二级权限  -->
                <el-row :class="[i2 === 0? '' :'bdTop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!--  渲染二级权限  -->
                  <el-col span="6">
                    <el-tag @close="removeRightById(scope.row,item2.id)" type="success" closable>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col span="18">
                    <!--  渲染三级权限  -->
                    <el-tag type="warning" v-for="(item3) in item2.children"
                            @close="removeRightById(scope.row,item3.id)" :key="item3.id" closable>{{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!--  通过scope获取作用域插槽数据 -->

          <template slot-scope="scope">
            <el-button type="primary" @click="showRoleEdit(scope.row.id)" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-star-off" size="mini" @click="showSetRightDialog(scope.row) ">分配权限</el-button>
          </template>

        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="500px"
      @close="addDialogClosed">
      <el-form ref="addRoleFormRef" :model="addRoleForm" :rules="addRoleRules" label-width="auto">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="500px">
      <el-form ref="editRoleFormRef" :model="editRoleForm" :rules="addRoleRules" label-width="auto">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRole">确 定</el-button>
  </span>
    </el-dialog>
    <!--  分配角色对话框  -->
    <el-dialog
      title="提示"
      :visible.sync="setRoleRightDialogVisible"
      @close="setRightDialogClosed"
      width="500px">
      <!--   树形控件   -->
      <el-tree :data="rightList" :props="treeProps"
               show-checkbox  node-key="id" default-expand-all
               :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';

export default {
  data () {
    return {
      // 所有角色列表数据
      roleList: [],
      // 控制添加角色对话框的显示与隐藏
      addRoleDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加用户的表单数据的验证
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      // 是否指定属性是看先获得数据还是先绑定数据
      editRoleForm: {
      },
      // 控制修改角色对话框的显示与隐藏
      editRoleDialogVisible: false,
      loading: false,
      // 控制分配角色对话框的显示与隐藏
      setRoleRightDialogVisible: false,
      // 所有权限的数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        // 要展示哪个属性
        label: 'authName',
        // 通过什么属性传递
        children: 'children'
      },
      // 默认选择中的节点id值
      defaultKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    };
  },
  created () {
    this.getRoleList();
  },
  methods: {
    // 获取的角色列表 角色名称 - 描述
    async getRoleList () {
      const { data: res } = await axios.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!');
      }
      this.roleList = res.data;
      console.log(res.data);
    },
    // 删除角色id对应权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限，是否继续？', '确认信息', {
        distinguishCancelAndClose: true,
        cancelButtonText: '否',
        confirmButtonText: '是',
        type: 'error'
      }).catch(err => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除');
      }
      const { data: res } = await axios.delete(`roles/${role.id}/rights/${rightId}`);
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败!');
      }
      // this.getRoleList()
      // ?为什么删除之后不能立即渲染呢？
      // 删除之后会重新获取数据列表，table表格会重新渲染一次，所以打开的状态被取消了
      role.children = res.data;
      // 不用刷新界面 提升用户体验
    },
    // 监听对话框关闭的事件
    addDialogClosed () {
      this.$refs.addRoleFormRef.resetFields();
    },
    // 权限对话框关闭事件 一定要关闭 !!!  数组的存入采用的是push 会在越来越多  所以在关闭的时候要清空数组!!!!
    setRightDialogClosed () {
      this.defaultKeys = [];
    },
    // 添加角色权限
    addRole () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await axios.post('roles', this.addRoleForm);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败!');
        }
        this.$message.success('添加角色成功!');
        this.addRoleDialogVisible = false;
        this.getRoleList();
      });
    },
    // 显示出编辑界面
    async showRoleEdit (id) {
      const { data: res } = await axios.get(`roles/${id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败!');
      }
      this.editRoleForm = res.data;
      this.editRoleDialogVisible = true;
    },
    // 修改用户成功
    editRole () {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return;
        // 发起修改角色的请求
        const { data: res } = await axios.put(`roles/${this.editRoleForm.roleId}`, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        });
        console.log(res);
        console.log(this.editRoleForm);
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败');
        }
        this.editRoleDialogVisible = false;
        // 刷新列表
        this.getRoleList();
        this.$message.success('修改角色信息成功');
      });
    },

    // 删除角色
    async removeRoleById (id) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'error'
      }).catch(err => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除');
      }
      const { data: res } = await axios.delete(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败!');
      }
      this.$message.success('删除角色成功!');
      // 刷新角色列表
      this.getRoleList();
    },
    // 展示分配角色对话框
    async showSetRightDialog (role) {
      this.roleId = role.id;
      const { data: res } = await axios.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败!');
      }
      this.rightList = res.data;
      console.log(this.rightList);
      // 递归获得三级节点id
      this.getLeafKeys(role, this.defaultKeys);
      console.log(role);
      this.setRoleRightDialogVisible = true;
    },
    // 通过递归的形式获取角色下所有三级权限id并保存到数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr));
    },

    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      console.log(keys);
      const idStr = keys.join(',');
      console.log(idStr);
      const { data: res } = await axios.post(`roles/${this.roleId}
      /rights`, { rids: idStr });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败!');
      }
      this.$message.success('分配权限成功!');
      this.getRoleList();
      this.setRoleRightDialogVisible = false;
    }
  }

};
</script>

<style lang="less" scoped>

.el-tag {
  margin: 7px;
}

.bdTop {
  border-top: 1px solid #409eff;
}
.bdBottom{
  border-bottom: 1px solid #409eff;
}
.vcenter{
  display: flex;
  align-items: center;
}
span{
  font-weight: bold;
  color: #409eff;
}

</style>
